<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>vant上传组件</title>
  </head>
  <body>
    <div id="app">
      <!-- vant上传组件
       van-uploader
          :before-read:上传前处理(file)=>{file.type:文件类型  file.size:文件大小(字节)
           return boolean   
           true:正常允许上传
           false:中止上传
        }
        after-read:它是指文件读取完成(表示 前面的before-read return true),(res)=>{resd.content:base64的文件(上传文件的二进制格式),res.file:文件对象}  往往用于调用上传接口
         :max-count="限制上传张数" 
         v-model="fileList"  双向绑定上传数据
      -->
      <van-uploader
        :before-read="beforeRead"
        :after-read="afterRead"
        :max-count="1"
        v-model="fileList"
      ></van-uploader>
    </div>
    <!-- 引入样式文件 -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/vant@2.10/lib/index.css"
    />

    <!-- 引入 Vue 和 Vant 的 JS 文件 -->
    <script src="./node_modules/axios/dist/axios.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vant@2.10/lib/vant.min.js"></script>
    <script>
      new Vue({
        el: '#app',
        data: {
          fileList: [
            {
              url:
                'http://localhost:1337/uploads/5a05a339bcf23d353905c5dd4234fb28_5eb1458986.png'
            }
          ]
        },
        methods: {
          beforeRead (file) {
            const isImg =
              file.type === 'image/png' || file.type === 'image/jpeg'
            const limit1M = file.size / 1024 / 1024 < 1
            if (!isImg) {
              this.$toast.fail('请上传PNG.JPG格式图片')
            }
            if (!limit1M) {
              this.$toast.fail('请上传1M以内图片')
            }
            return isImg && limit1M
          },
          afterRead (res) {
            // window.console.log(res.file)
            const _formdata = new FormData()
            _formdata.append('files', res.file)
            axios({
              url: 'http://localhost:1337/upload',
              method: 'post',
              headers: {
                authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6OCwiaWF0IjoxNjA0ODA3MDgxLCJleHAiOjE2MDczOTkwODF9.P_8cSBnWYyJpQTjzGPxd0HlfPM-qwwv70m1HjZE-Nmo`
              },
              data: _formdata
            }).then(res => {
              window.console.log(res)
            })
          }
        }
      })
    </script>
  </body>
</html>
